package com.captain.special.栈队列;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/4/7 0:01
 */
public class 前K个高频元素347 {

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>(nums.length / 2);
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        //构建小堆 1 - 2
        Comparator<int[]> comparator = Comparator.comparingInt(o -> o[1]);
        //优先队列
        PriorityQueue<int[]> queue = new PriorityQueue<>(comparator);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            Integer key = entry.getKey();
            Integer count = entry.getValue();
            //队列中最多包含k个数
            if (queue.size() < k) {
                queue.offer(new int[]{key, count});
            } else {
                if (queue.peek()[1] < count) {
                    queue.poll();
                    queue.add(new int[]{key, count});
                }
            }
        }
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = queue.poll()[0];
        }
        return res;
    }
}
